const ADD_SEARCH = "ADD_SEARCH";
const DELETE_SEARCH = "DELETE_SEARCH";
const CLEAR_SEARCH = "CLEAR_SEARCH";

interface AddSearchType {
  type: typeof ADD_SEARCH;
  payload: string;
}
export function addSearchActionCreator(payload: string): AddSearchType {
  return { type: ADD_SEARCH, payload };
}

interface DeleteSearchType {
  type: typeof DELETE_SEARCH;
  payload: string;
}

export function deleteSearchActionCreator(payload: string): DeleteSearchType {
  return { type: DELETE_SEARCH, payload };
}

interface ClearSearchType {
  type: typeof CLEAR_SEARCH;
}

export function clearSearchActionCreator(): ClearSearchType {
  return { type: CLEAR_SEARCH };
}

type SearchAction = AddSearchType | DeleteSearchType | ClearSearchType;

interface SearchState {
  search: string[];
}

const initState: SearchState = {
  search: [],
};

export default (state = initState, action: SearchAction) => {
  switch (action.type) {
    case ADD_SEARCH: {
      return {
        ...state,
        search: [...(new Set([action.payload, ...state.search]) as any)],
      };
    }
    case DELETE_SEARCH: {
      return {
        ...state,
        search: state.search.filter((v) => v !== action.payload),
      };
    }

    case CLEAR_SEARCH: {
      return {
        search: [],
      };
    }
    default:
      return state;
  }
};
